package com.xingfei.blog.service;

import com.xingfei.blog.constants.ErrorConstants;
import com.xingfei.blog.controller.message.WebSocket;
import com.xingfei.blog.dto.SecretMessageDTO;
import com.xingfei.blog.dto.UserAttentionDTO;
import com.xingfei.blog.result.ServiceResult;
import com.xingfei.blog.vo.UserAttentionVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Created with IntelliJ IDEA.
 *
 * @author: chenxingfei
 * @time: 2017/4/3  21:28
 * To change this template use File | Settings | File Templates.
 */
@Service("webAttentionService")
public class WebAttentionService {

    @Autowired
    private BlogUserAttentionService blogUserAttentionService;
    @Autowired
    private BlogSecretMessageService blogSecretMessageService;
    @Autowired
    private WebUserService webUserService;
    @Autowired
    private WebSocket webSocket;

    /**
     * 关注或取消关注
     *
     * @param userAttentionVo
     * @return
     */
    public boolean addOrDeleteAttention(UserAttentionVo userAttentionVo) {
        boolean attention = userAttentionVo.isAttention();
        boolean result = false;
        UserAttentionDTO userAttentionDTO = new UserAttentionDTO();
        BeanUtils.copyProperties(userAttentionVo, userAttentionDTO);
        ServiceResult<UserAttentionDTO> attentionsResult = null;
        //关注
        if (attention) {
            attentionsResult = this.blogUserAttentionService.saveAttention(userAttentionDTO);
        }
        //取消关注
        else {
            attentionsResult = this.blogUserAttentionService.removeAttention(userAttentionDTO);
            //处理关注结果
        }
        if (attentionsResult != null && attentionsResult.getCode() == ErrorConstants.RES_SUCCESS) {
            /*UserAttentionDTO attentionDTO = attentionsResult.getResult();
            if (attentionDTO != null) {
                sendSecretMessage(attention, attentionDTO);
                result = true;
            }*/
            //处理关注 发送消息通知被关注者
            webSocket.attentionWS("您有新的关注者to"+userAttentionVo.getByAttentionId());
            result = true;
            //取消关注无需发送私信
        }
        return result;
    }

    /**
     * 关注成功后给被关注用户发送私信通知
     *
     * @param attention
     * @param attentionDTO
     */
    private void sendSecretMessage(boolean attention, UserAttentionDTO attentionDTO) {
        if (attention) {
            //给用户发送私信
            SecretMessageDTO secretMessageDTO = new SecretMessageDTO();
            secretMessageDTO.setSendId(attentionDTO.getAttentionId());
            secretMessageDTO.setReceiveId(attentionDTO.getByAttentionId());
            secretMessageDTO.setMessageTopic("被其他用户关注");
            secretMessageDTO.setMessageContent(" 关注了你");
            blogSecretMessageService.saveSecretMessage(secretMessageDTO);
        }
    }
}
